﻿using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web.Script.Serialization;
using System.Xml.Serialization;
using Ctef.Web.Models;

namespace Ctef.Web.Repositories
{
    public class SchoolRepository
    {
        private static SchoolRepository instance;
        private static object sync = new object();

        private List<School> schools;

        private SchoolRepository()
        {
        }

        public static SchoolRepository Instance
        {
            get
            {
                if (instance != null)
                {
                    return instance;
                }

                lock (sync)
                {
                    if (instance == null)
                    {
                        instance = new SchoolRepository();
                    }

                }

                return instance;
            }
        }

        public string SchoolDataJson
        {
            get
            {
                return new JavaScriptSerializer()
                        .Serialize(
                        schools.Select(s => new { name = s.Name, intro = s.Introduction, lon = s.Longtitude, lat = s.Latitude }));
            }
        }

        public void Initialize(string path)
        {
            if (schools != null)
            {
                return;
            }

            lock (sync)
            {
                if (schools != null)
                {
                    return;
                }

                var file = "schoolinfo.xml";

                using (var text = new FileStream(Path.Combine(path, file), FileMode.Open, FileAccess.Read))
                {
                    var ser = new XmlSerializer(typeof(List<School>));
                    schools = (List<School>)ser.Deserialize(text);
                }
            }
        }
    }
}